//
//  QRCodeViewController.swift
//  weibo
//
//  Created by sanya on 15/6/29.
//  Copyright © 2015年 sanya. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController,UITabBarDelegate,AVCaptureMetadataOutputObjectsDelegate {
    @IBOutlet weak var tabbar: UITabBar!

    @IBOutlet weak var widthConstraint: NSLayoutConstraint!

    @IBOutlet weak var resultLabel: UILabel!
    
    @IBOutlet weak var heighConstraint: NSLayoutConstraint!
    // 顶部约束
    @IBOutlet weak var topContraint: NSLayoutConstraint!
    @IBOutlet weak var scanView: UIImageView!
    // 关闭视图
    @IBAction func close(sender: AnyObject) {
        dismissViewControllerAnimated(true, completion: nil)

    }
    
    
    @IBAction func showMycar(sender: AnyObject) {
     navigationController?.pushViewController(QRCodeMyCardViewController(), animated: true)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // 默认选中第一项
        tabbar.selectedItem = tabbar.items![0]
        setupSestion()
        setupLayers()
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
        

    }
    func startAnimation(){
        topContraint.constant = -heighConstraint.constant
        self.view.layoutIfNeeded()
        
        UIView.animateWithDuration(2.0) { () -> Void in
            // 重复次数需要放在内部
            UIView.setAnimationRepeatCount(MAXFLOAT)
            
            // 添加了修改的标记
            self.topContraint.constant = self.heighConstraint.constant
            self.view.layoutIfNeeded()
        }
    }
    override func viewDidAppear(animated: Bool) {
        startAnimation()
        startScan()

    }
    /// 设置图层
    private func setupLayers() {
        // 1. 设置绘图图层
        drawLayer.frame = view.bounds
        view.layer.insertSublayer(drawLayer, atIndex: 0)
        
        // 预览图层
        previewLayer.frame = view.bounds
        // 设置图层填充模式
        previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        view.layer.insertSublayer(previewLayer, atIndex: 0)
    }
    /// 开始扫描
    func startScan() {
        session.startRunning()
    }
    
    /// 设置会话
    func setupSestion(){
        // 1. 判断能否添加输入设备
        if !session.canAddInput(inputDevice){
            print("无法添加输入设备")
            return
        }
        // 2. 判断能否添加输出设备
        if !session.canAddOutput(outputData){
            print("无法添加输入数据")
            return
        }
        // 3. 添加设备
        session.addInput(inputDevice)
        session.addOutput(outputData)
        // 4. 设置检测数据类型，检测所有支持的数据格式
        outputData.metadataObjectTypes = outputData.availableMetadataObjectTypes
        // 5. 设置数据的代理
        outputData.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
    }
    
    // MARK: - 代理方法  AVCaptureMetadataOutputObjectsDelegate
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        
        // 清除绘图图层
        clearDrawLayer()
        
        for object in metadataObjects{
            if object is AVMetadataMachineReadableCodeObject {
                // 转换数据类型
                let codeObject = previewLayer.transformedMetadataObjectForMetadataObject(object as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject
                drawCorners(codeObject)
                resultLabel.text = codeObject.stringValue
            }
        }
    }
    /// 清除绘图图层
    private func clearDrawLayer() {
        if drawLayer.sublayers == nil{
            return
        }
        for subayer in drawLayer.sublayers! {
            subayer.removeFromSuperlayer()
        }
    }
    
    /// 绘制扫描形状
    private func drawCorners(codeObject:AVMetadataMachineReadableCodeObject){
        // 可以做动画绘图的， 专门在图层中画图
        let layer = CAShapeLayer()
        layer.lineWidth = 4
        layer.strokeColor = UIColor.greenColor().CGColor
        layer.fillColor = UIColor.clearColor().CGColor
        // codeObject是一个 包含 CFDictionaries 的 NSArray
        layer.path = creatPath(codeObject.corners).CGPath
        drawLayer.addSublayer(layer)
    }
    private func creatPath(corners:NSArray) -> UIBezierPath{
    
        let path = UIBezierPath()
        var point = CGPoint()
        var index = 0
        // 拿到第一个点
        CGPointMakeWithDictionaryRepresentation(corners[index++] as! CFDictionary, &point)
        path.moveToPoint(point)
        // 遍历所有的点
        while index < corners.count{
            CGPointMakeWithDictionaryRepresentation(corners[index++] as! CFDictionary, &point)
            path.addLineToPoint(point)
        }
        // 关闭路径
        path.closePath()
        
        return path
    }
    
    /// tabBar的代理方法
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        // 调整高度
        heighConstraint.constant = widthConstraint.constant * (item.tag == 1 ? 0.5 : 1)
        // 停止动画 -- 核心动画将动画添加到图层
        scanView.layer.removeAllAnimations()
        
        startAnimation()
    }
    /// 懒加载
    
    // 会话视图
    lazy var drawLayer:CALayer = CALayer()
    // 预览视图
    lazy var previewLayer:AVCaptureVideoPreviewLayer = {
        AVCaptureVideoPreviewLayer(session: self.session)
    
    }()
    // session 桥梁
    lazy var session:AVCaptureSession = AVCaptureSession()
    // 输入设备
    lazy var inputDevice:AVCaptureDeviceInput? = {
    
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        do{
            return try AVCaptureDeviceInput(device: device)
        }catch{
            return nil
        }
    }()
    // 输出数据
    lazy var outputData:AVCaptureMetadataOutput = AVCaptureMetadataOutput()
}
